﻿/*----------------------------------------------------------------
    // Copyright (C) 2009 江苏华招网
    // 版权所有。 
    // 作者：庄金冬 
    //
    // 文件名：DAL_Role.cs
    // 文件功能描述：角色数据访问逻辑
    // 创建标识：庄金冬2009-03-06
    //
    // 修改标识：
    // 修改描述：
    //
    // 修改标识：
    // 修改描述：
    //
    // 审核人：
    // 审核时间：
    // 审核说明：
 //----------------------------------------------------------------*/
using System;
using System.Collections.Generic;

using System.Text;
using HZ.Supervise.Model;
using HZ.Common;
using System.Data;
using System.Data.SqlClient;
namespace HZ.Supervise.DAL
{
    /// <summary>
    /// 角色数据访问逻辑
    /// </summary>
    public class DAL_Role
    {
        /// <summary>
        /// 添加角色同时可添加权限信息
        /// </summary>
        /// <param name="role">角色实体（可含权限信息）[RoleID不用赋值，由系统自动生成]</param>
        /// <returns>0不成功;1成功;2该名称已经存在</returns>
        public static int AddRole(Role role)
        {
            int retValue = 0;
            try
            {
                SqlParameter[] paras = new SqlParameter[4];

                paras[0] = new SqlParameter("@in_RoleID", string.IsNullOrEmpty(role.RoleID) ? "" : role.RoleID.Trim());

                paras[1] = new SqlParameter("@in_RoleName", string.IsNullOrEmpty(role.RoleName) ? "" : role.RoleName.Trim());

                //处理权限编号
                StringBuilder sbOperatingRuleIDs = new StringBuilder("");
                string strOperatingRuleIDs = "";
                if (role.OperatingRuleList != null)
                {
                    if (role.OperatingRuleList.Count > 0)
                    {
                        foreach (OperatingRule operatingRule in role.OperatingRuleList)
                        {
                            sbOperatingRuleIDs.Append(operatingRule.OperatingRuleID + ",");
                        }

                        strOperatingRuleIDs = sbOperatingRuleIDs.ToString().Trim().Substring(0, sbOperatingRuleIDs.Length - 1);

                    }
                }

                //
                paras[2] = new SqlParameter("@OperatingRuleIDs", strOperatingRuleIDs);

                paras[paras.Length - 1] = new SqlParameter("@out_success", SqlDbType.Int);

                paras[paras.Length - 1].Direction = ParameterDirection.Output;


                //执行存储过程
                HZ.Data.DbHelperFactory.Create().ExecuteNonQuery(CommandType.StoredProcedure, "usp_Role_Add", paras);

                retValue = int.Parse(paras[paras.Length - 1].Value.ToString());
            }
            catch (Exception ex)
            {
                //执行不成功，记录日志 
                log4netManager.LogDebug(typeof(DAL_Role).FullName, "添加角色不成功", ex);
            }

            return retValue;
        }


        /// <summary>
        /// 设定角色的操作权限(连带更新)
        /// </summary>
        /// <param name="role">带角色操作权限的角色对象</param>
        /// <returns></returns>
        public static bool SetRoleOperatingRule(Role role)
        {
            int retValue = 0;
            try
            {
                SqlParameter[] paras = new SqlParameter[3];

                if (role!=null)
                {
                    if (string.IsNullOrEmpty(role.RoleID))
                    {
                        new Exception("角色相关信息为空，设定角色权限信息必须提供角色信息，故系统阻止继续操作！");
                    }
                    paras[0] = new SqlParameter("@in_RoleID", string.IsNullOrEmpty(role.RoleID) ? "" : role.RoleID.Trim());
                }
                else
                {
                    new Exception("角色相关信息为空，设定角色权限信息必须提供角色信息，故系统阻止继续操作！");
                }              

                //处理权限编号
                StringBuilder sbOperatingRuleIDs = new StringBuilder("");
                string strOperatingRuleIDs = "";
                if (role.OperatingRuleList != null)
                {
                    if (role.OperatingRuleList.Count > 0)
                    {
                        foreach (OperatingRule operatingRule in role.OperatingRuleList)
                        {
                            sbOperatingRuleIDs.Append(operatingRule.OperatingRuleID + ",");
                        }

                        strOperatingRuleIDs = sbOperatingRuleIDs.ToString().Trim().Substring(0, sbOperatingRuleIDs.Length - 1);

                    }
                }

                //
                paras[1] = new SqlParameter("@OperatingRuleIDs", strOperatingRuleIDs);

                paras[paras.Length - 1] = new SqlParameter("@out_success", SqlDbType.Int);

                paras[paras.Length - 1].Direction = ParameterDirection.Output;


                //执行存储过程
                HZ.Data.DbHelperFactory.Create().ExecuteNonQuery(CommandType.StoredProcedure, "usp_RoleRule_Add", paras);

                retValue = int.Parse(paras[paras.Length - 1].Value.ToString());
            }
            catch (Exception ex)
            {
                //执行不成功，记录日志 
                log4netManager.LogDebug(typeof(DAL_Role).FullName, "设置角色权限不成功", ex);
            }

            return retValue == 1 ? true : false;
        }

        /// <summary>
        /// 设定角色名称及操作权限(连带更新)[0,更新失败;1,更新成功;2,该角色名称已经存在3,该角色已经不存在]
        /// </summary>
        /// <param name="role">带角色操作权限的角色对象</param>
        /// <returns>0,更新失败;1,更新成功;2,该角色名称已经存在3,该角色已经不存在</returns>
        public static int SetRole_OperatingRule(Role role)
        {
            int retValue = 0;
            try
            {
                SqlParameter[] paras = new SqlParameter[4];

                if (role != null)
                {
                    if (string.IsNullOrEmpty(role.RoleID))
                    {
                        new Exception("角色相关信息为空，设定名称及操作权限信息必须提供角色信息，故系统阻止继续操作！");
                    }
                    paras[0] = new SqlParameter("@in_RoleID", string.IsNullOrEmpty(role.RoleID) ? "" : role.RoleID.Trim());
                    paras[1] = new SqlParameter("@in_RoleName", string.IsNullOrEmpty(role.RoleName) ? "" : role.RoleName.Trim());
                }
                else
                {
                    new Exception("角色相关信息为空，设定名称及操作权限必须提供角色信息，故系统阻止继续操作！");
                }

                //处理权限编号
                StringBuilder sbOperatingRuleIDs = new StringBuilder("");
                string strOperatingRuleIDs = "";
                if (role.OperatingRuleList != null)
                {
                    if (role.OperatingRuleList.Count > 0)
                    {
                        foreach (OperatingRule operatingRule in role.OperatingRuleList)
                        {
                            sbOperatingRuleIDs.Append(operatingRule.OperatingRuleID + ",");
                        }

                        strOperatingRuleIDs = sbOperatingRuleIDs.ToString().Trim().Substring(0, sbOperatingRuleIDs.Length - 1);

                    }
                }

                //
                paras[2] = new SqlParameter("@OperatingRuleIDs", strOperatingRuleIDs);

                paras[paras.Length - 1] = new SqlParameter("@out_success", SqlDbType.Int);

                paras[paras.Length - 1].Direction = ParameterDirection.Output;


                //执行存储过程
                HZ.Data.DbHelperFactory.Create().ExecuteNonQuery(CommandType.StoredProcedure, "usp_Role_Rule_Update", paras);

                retValue = int.Parse(paras[paras.Length - 1].Value.ToString());
            }
            catch (Exception ex)
            {
                //执行不成功，记录日志 
                log4netManager.LogDebug(typeof(DAL_Role).FullName, "设置角色名称及权限不成功", ex);
            }

            return retValue ;
        }

        /// <summary>
        /// 设定角色名称[0,更新失败;1,更新成功;2,该角色名称已经存在3,该角色已经不存在]
        /// </summary>
        /// <param name="role">角色对象</param>
        /// <returns>0,更新失败;1,更新成功;2,该角色名称已经存在3,该角色已经不存在</returns>
        public static int SetRole(Role role)
        {
            int retValue = 0;
            try
            {
                SqlParameter[] paras = new SqlParameter[3];

                if (role != null)
                {
                    if (string.IsNullOrEmpty(role.RoleID))
                    {
                        new Exception("角色相关信息为空，设定名称及操作权限信息必须提供角色信息，故系统阻止继续操作！");
                    }
                    paras[0] = new SqlParameter("@in_RoleID", string.IsNullOrEmpty(role.RoleID) ? "" : role.RoleID.Trim());
                    paras[1] = new SqlParameter("@in_RoleName", string.IsNullOrEmpty(role.RoleName) ? "" : role.RoleName.Trim());
                }
                else
                {
                    new Exception("角色相关信息为空，设定名称及操作权限必须提供角色信息，故系统阻止继续操作！");
                }

                paras[paras.Length-1] = new SqlParameter("@out_success", SqlDbType.Int);

                paras[paras.Length - 1].Direction = ParameterDirection.Output;


                //执行存储过程
                HZ.Data.DbHelperFactory.Create().ExecuteNonQuery(CommandType.StoredProcedure, "usp_Role_Update", paras);

                retValue = int.Parse(paras[paras.Length - 1].Value.ToString());
            }
            catch (Exception ex)
            {
                //执行不成功，记录日志 
                log4netManager.LogDebug(typeof(DAL_Role).FullName, "设置角色名称及权限不成功", ex);
            }

            return retValue;
        }


        /// <summary>
        /// 删除角色(0.不成功,1.不成功,2.角色不存在,3.该角色已被用户使用，不能删除)
        /// </summary>
        /// <param name="roleid">角色编号</param>
        /// <returns>(0.不成功,1.不成功,2.角色不存在,3.该角色已被用户使用，不能删除)</returns>
        public static int DeleteRole(string roleid)
        {
            int retValue = 0;

            SqlParameter[] paras = new SqlParameter[2];
            if (string.IsNullOrEmpty(roleid))
            {
                retValue = 2;
                new Exception("角色相关信息为空，删除角色权限信息必须提供角色信息，故系统阻止继续操作！");
            }
            paras[0] = new SqlParameter("@in_RoleID", string.IsNullOrEmpty(roleid) ? "" : roleid.Trim());
            paras[1] = new SqlParameter("@out_success", SqlDbType.Int, 4);
            paras[1].Direction = ParameterDirection.Output;

            try
            {
                //执行存储过程
                HZ.Data.DbHelperFactory.Create().ExecuteNonQuery(CommandType.StoredProcedure, "usp_Role_Del", paras);
                retValue = int.Parse(paras[1].Value.ToString());
            }
            catch (Exception ex)
            {
                //执行不成功，记录日志 
                log4netManager.LogDebug(typeof(DAL_Role).FullName, "删除角色失败", ex);
            }

            return retValue;
        }

        /// <summary>
        /// 获取所有角色
        /// </summary>
        /// <returns></returns>
        public static IList<Role> GetAllRole(int currentPage, int pageSize, out int totalRecord)
        {
            string sql_GetAllRole = @"SELECT * FROM TB_Role WHERE 1=1  ORDER BY RoleID";

            totalRecord = HZ.Data.DbHelperFactory.Create().ExecuteTable(sql_GetAllRole).Rows.Count;

            HZ.Data.PageDescribe pdes = new HZ.Data.PageDescribe(sql_GetAllRole, pageSize);

            pdes.CurrentPage = currentPage;

            IList<Role> list;
            DataTable dt = pdes.GetSpecailPage();
            list = DAL_Helper.GetRolesFromDataTable(dt);
            return list;
           
        }


        /// <summary>
        /// 根据角色编号获取该角色(包括操作权限)
        /// </summary>
        /// <param name="roleid">角色编号</param>
        /// <returns>角色(包括操作权限)</returns>
        public static Role GetRole_OperatingRule_ByRoleID(string roleid)
        {
            Role role = new Role();

            string sql_role = @"SELECT [RoleID],[RoleName],[IsDefault] FROM [dbo].[TB_Role] WHERE  [RoleID]='{0}'";

            string sql_operatingRule = @"SELECT     OperatingRuleID, OperatingRuleName, 
                                           Module, ComFlag, CenFlag, HosFlag
                                FROM  dbo.View_RoleRule WHERE  [RoleID]='{0}'";

            StringBuilder sb_roleWhere = new StringBuilder("");
            StringBuilder sb_operatingRuleWhere = new StringBuilder("");

            if (!string.IsNullOrEmpty(roleid))
            {
                sb_roleWhere.AppendFormat(sql_role, roleid); // 增加UserID查询条件  
                sb_operatingRuleWhere.AppendFormat(sql_operatingRule, roleid); // 增加UserID查询条件  
            }

            DataTable dt1 = HZ.Data.DbHelperFactory.Create().ExecuteTable(sb_roleWhere.ToString());
            DataTable dt2 = HZ.Data.DbHelperFactory.Create().ExecuteTable(sb_operatingRuleWhere.ToString());
            role = DAL_Helper.GetRoleFromDataRow(dt1,dt2);
           
            return role;
        }

        /// <summary>
        /// 根据角色编号获取该角色的操作权限
        /// </summary>
        /// <param name="roleid">角色编号</param>
        /// <returns>操作权限集合</returns>
        public static IList<OperatingRule> GetRoleOperatingRuleByRoleID(string roleid)
        {
            string sql_operatingRule = @"SELECT OperatingRuleID, OperatingRuleName, 
                                           Module, ComFlag, CenFlag, HosFlag,Manflag
                                FROM  dbo.View_RoleRule WHERE Manflag = 1 and [RoleID]='{0}' and operatingruleid not in('90001','90002','90005')";
            //[RoleID]='{0}'and 
          
            StringBuilder sb_operatingRuleWhere = new StringBuilder("");

            if (!string.IsNullOrEmpty(roleid))
            {
               sb_operatingRuleWhere.AppendFormat(sql_operatingRule, roleid); // 增加UserID查询条件  
            }
                       
            DataTable dt = HZ.Data.DbHelperFactory.Create().ExecuteTable(sb_operatingRuleWhere.ToString());
            IList<OperatingRule> list = DAL_Helper.GetOperatingRulesFromDataTable(dt);
            return list;
        }

    }
}
